<template>
  <div class="component-upload-image">
    <el-upload
        ref="imageUpload"
        :action="state.uploadImgUrl"
        :before-upload="handleBeforeUpload"
        :class="{hide: state.fileList.length >= props.limit}"
        :file-list="state.fileList"
        :headers="state.headers"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleDelete"
        :on-success="handleUploadSuccess"
        :show-file-list="true"
        list-type="picture-card"
        multiple
    >
      <el-icon class="avatar-uploader-icon">
        <ele-Plus/>
      </el-icon>
    </el-upload>

    <!-- 上传提示 -->
    <div v-if="showTip" class="el-upload__tip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
      的文件
    </div>

    <el-dialog
        v-model:visible="state.dialogVisible"
        append-to-body
        title="预览"
        width="800"
    >
      <img
          :src="state.dialogImageUrl"
          style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts" name="imageUploadRef" setup>

import {computed, reactive, ref, watch} from "vue";
import {Session} from "/@/utils/storage";
import type {UploadInstance} from 'element-plus'
import {ElLoading, ElMessage} from "element-plus";
import {ossApi} from "/@/api/sys/oss";

// 定义子组件向父组件传值/事件
const emit = defineEmits(['update']);

const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["png", "jpg", "jpeg"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  }
});

watch(() => props.modelValue, (val) => {
  if (val) {
    // 首先将值转为数组
    let list;
    if (Array.isArray(val)) {
      list = val;
    } else {
      ossApi().listByUrls(val.split(',')).then(res => {
        list = res.data;
        // 然后将数组转为对象数组
        state.fileList = list.map(item => {
          // 此处name使用id 防止删除出现重名
          item = {name: item.id, url: item.url, id: item.id};
          return item;
        });
      })
    }
  } else {
    state.fileList = [];
    return [];
  }
});

const loadingInstance = ref();
const imageUpload = ref<UploadInstance>();
const state = reactive({
  number: 0,
  uploadList: [],
  dialogImageUrl: "",
  dialogVisible: false,
  hideUpload: false,
  uploadImgUrl: import.meta.env.VITE_API_URL + "/oss/upload",
  headers: {
    Authorization: Session.get('token'),
  },
  fileList: []
})

// 获取布局配置信息
const showTip = computed(() => {
  return props.isShowTip && (props.fileType || props.fileSize);
});

const handleBeforeUpload = (file: any) => {
  let isImg = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isImg = props.fileType.some((type: any) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf("image") > -1;
  }
  if (!isImg) {
    ElMessage.error(`文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`);
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      ElMessage.error(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  loadingInstance.value = ElLoading.service({lock: true, text: "正在上传图片，请稍候..."});
  state.number++;
}

// 文件个数超出
const handleExceed = () => {
  ElMessage.error(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传成功回调
const handleUploadSuccess = (res: any, file: any) => {
  if (res.code === 200) {
    state.uploadList.push(
        {
          name: res.data.fileName,
          url: res.data.url,
          id: res.data.id
        }
    );
    uploadedSuccessfully();
  } else {
    state.number--;
    loadingInstance.value.close();
    ElMessage.error(res.msg);
    imageUpload.value!.handleRemove(file);
    uploadedSuccessfully();
  }
}

// 删除图片
const handleDelete = (file: any, files: any) => {
  ossApi().delOss(file);
  emit('update:modelValue', listToString(files, ","));
}

const handleUploadError = () => {
  ElMessage.error("上传图片失败，请重试");
  loadingInstance.value.close();
}

const uploadedSuccessfully = () => {
  if (state.number > 0 && state.uploadList.length === state.number) {
    state.fileList = state.fileList.concat(state.uploadList);
    state.uploadList = [];
    state.number = 0;
    emit('update:modelValue', listToString(state.fileList, ","));
    loadingInstance.value.close();
  }
}

// 预览
const handlePictureCardPreview = (file: any) => {
  state.dialogImageUrl = file.url;
  state.dialogVisible = true;
}

// 对象转成指定字符串分隔
const listToString = (list: any, separator: any) => {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator;
    }
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}

</script>
<style lang="scss" scoped>
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}

// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
</style>

